<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<style type="text/css">
		 #console-container {
            width: 400px;
        }
        #console {
            border: 1px solid #CCCCCC;
            border-right-color: #999999;
            border-bottom-color: #999999;
            height: 170px;
            overflow-y: scroll;
            padding: 5px;
            width: 100%;
        }
        #console p {
            padding: 0;
            margin: 0;
        }
	</style>
	<script type="text/javascript">
		var ws=null;
		function startServer(){
			var url="ws://127.0.0.1:8080/WebSocket/chat.ws";
			
			if("WebSocket" in window){
				ws=new WebSocket(url);
			}else if("MozWebSocket" in window ){
				ws=new MozWebSocket(url);
			}else{
				alert("buzhichi");
				return ;
			}
			ws.onopen=function(){
				alert("opened!");
			};
			ws.onmessage = function(event) {
				Console.log(event.data);
            };
			ws.onclose=function(){
				alert("close!");
			};
		}
		function sendMyMessage(){
			var textMessage=document.getElementById("text").value;
			if(ws!=null&&textMessage!=""){
				ws.send(textMessage);
			}
		}
		var Console = {};
        Console.log = (function(message) {
            var console = document.getElementById('console');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.innerHTML = message;
            console.appendChild(p);
            while (console.childNodes.length > 25) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        });
        document.onkeydown=function enterHandler(event){
        	var keyCode=event.keyCode?event.keyCode:event.which?event.which:event.charCode;   
			if (keyCode == 116) {   
			 	  ws.close();
			}
			if(keyCode==13){
				sendMyMessage();
			}
			
		};   
        
		
	</script>
  </head>
  
  <body onload="startServer()">
    <input type="text" id="text" size="20" />
    <input type="button" onclick="sendMyMessage()" value="Send"/>
    <div id="console-container">
        <div id="console"></div>
    </div>
  </body>
</html>
